package com.itjeffrey.autocode.security;

import com.itjeffrey.autocode.bo.ResInfoTbBO;
import com.itjeffrey.autocode.common.BaseCommon;
import com.itjeffrey.autocode.bo.LoginInfoBO;
import com.itjeffrey.autocode.constant.SysConstant;
import com.itjeffrey.autocode.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户登录认证信息查询
 * @From: Jeffrey
 * @Date: 2020/12/01
 */
@Component
public class JwtUserDetailsService implements UserDetailsService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        LoginInfoBO user = BaseCommon.loginInfoMap.get(loginName);
        if (user == null) {
            logger.warn("用户[{}]不存在！", loginName);
            throw new UsernameNotFoundException(String.format("用户{%s}不存在!", loginName));
        }
         //用户资源列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口
        Set<String> permissions = userService.findPermission(userService.getUserNameByLoginName(loginName),
                SysConstant.RES_TYPE_JK);
        List<GrantedAuthority> grantedAuthorities = permissions.stream().map(ResInfoTbBO::new).collect(Collectors.toList());
        return new JwtUserDetails(loginName, user.getLoginPwd(), grantedAuthorities);
    }
}